import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';

class IOFileDemo extends MaterialPageRoute<Null> {
    IOFileDemo()
        : super(builder: (BuildContext ctx) {
        return Scaffold(
            appBar: AppBar(
                title: Text("文件读写"),
            ),
            body: IOFilePage(
                storage: MyStorage(),
            ),
        );
    });
}

class IOFilePage extends StatefulWidget {
    final MyStorage storage;
    
    IOFilePage({Key key, @required this.storage}) : super(key: key);
    
    @override
    State<StatefulWidget> createState() {
        return IOFileState();
    }
}

class IOFileState extends State<IOFilePage> {
    TextEditingController controller = TextEditingController();
    String state = "";
    Future<Directory> appTestDir;
    
    @override
    void initState() {
        super.initState();
        _read();
    }
    
    _read() async {
        widget.storage.readStringFromFile().then((onValue) {
            setState(() {
                state = onValue;
            });
        });
    }
    
    @override
    Widget build(BuildContext context) {
        return ListView(
            children: <Widget>[
                Container(
                    height: 50.0,
                    color: Colors.grey,
                    child: Row(
                        
                        children: <Widget>[
                            Text(
                                state,
                            ),
                        ],
                    ),
                ),
                TextField(
                    controller: controller,
                ),
                RaisedButton(
                    child: Text("read"),
                    onPressed: _read,
                ),
                RaisedButton(
                    child: Text("write"),
                    onPressed: () async {
                        setState(() {
                            state = controller.text;
                            controller.text = "";
                            widget.storage.writeStringToFile(state);
                        });
                    },
                ),
            ],
        );
    }
}

class MyStorage {
    Future<String> get localPath async {
        final dir = await getApplicationDocumentsDirectory();
        return dir.path;
    }
    
    Future<File> get localFile async {
        final path = await localPath;
        return File("$path/test.txt");
    }
    
    Future<String> readStringFromFile() async {
        try {
            final file = await localFile;
            String body = await file.readAsString();
            return body;
        } catch (e) {
            return '';
        }
    }
    
    Future<File> writeStringToFile(String str) async {
        final file = await localFile;
        return file.writeAsString(str);
    }
}
